import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';


Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    accessToken: localStorage.getItem('accessToken') || null,
    refreshToken: localStorage.getItem('refreshToken') || null
  },
  mutations: {
    setAccessToken(state, token) {
      state.accessToken = token;
      localStorage.setItem('accessToken', token);
    },
    setRefreshToken(state, token) {
      state.refreshToken = token;
      localStorage.setItem('refreshToken', token);
    }
  },
  actions: {
    checkTokenValidity({ state, dispatch }) {
      const accessToken = state.accessToken;
      if (accessToken) {
        const expirationTime = parseJwt(accessToken).exp;
        const currentTime = Math.floor(Date.now() / 1000);
        const timeLeft = expirationTime - currentTime;
        if (timeLeft <= 30) {
          return dispatch('refreshToken');
        } else {
          setTimeout(() => {
            dispatch('checkTokenValidity');
          }, timeLeft * 1000);
        }
      }
    },
    async refreshToken({ state, commit }) {
      const refreshToken = state.refreshToken;
      try {
        const response = await axios.post('/api/refresh-token', {
          refreshToken: refreshToken
        });
        const newAccessToken = response.data.newAccessToken;
        commit('setAccessToken', newAccessToken);
        return dispatch('checkTokenValidity');
      } catch (error) {
        console.log('刷新Token失败', error);
        return await Promise.reject(error);
      }
    }
  },
  getters: {
    isAuthenticated: state => state.accessToken!== null
  }
});

